<template>
  <div class="sales-outbound-container">
    <el-card class="header-card">
      <template #header>
        <div class="card-header">
          <span class="title">销售出库</span>
          <el-button type="primary" icon="Refresh" @click="loadShipments">刷新</el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="发货编号">
          <el-input v-model="searchForm.shipment_no" placeholder="请输入发货编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.order_no" placeholder="请输入订单编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.product_name" placeholder="请输入商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 发货列表 -->
    <el-card class="table-card">
      <el-table 
        :data="shipmentList" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="shipment_no" label="发货编号" width="150" align="center" />
        <el-table-column prop="order_no" label="订单编号" width="150" align="center" />
        <el-table-column prop="product_name" label="商品名称" width="200" align="center" />
        <el-table-column prop="Num" label="发货数量" width="100" align="center" />
        <el-table-column prop="unit_price" label="单价" width="120" align="center">
          <template #default="{ row }">
            ¥{{ row.unit_price ? row.unit_price.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="总金额" width="120" align="center">
          <template #default="{ row }">
            ¥{{ row.total_amount ? row.total_amount.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="Address" label="发货地址" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column prop="CreateDate" label="创建时间" width="180" align="center" />
        <el-table-column label="出库状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.outbound_status === 1 ? 'success' : 'warning'">
              {{ row.outbound_status === 1 ? '已出库' : '待出库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.outbound_status !== 1"
              type="primary" 
              size="small" 
              @click="handleOutbound(row)">
              出库
            </el-button>
            <el-button 
              v-else
              type="info" 
              size="small" 
              disabled>
              已出库
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.rows"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 批量出库按钮 -->
    <div class="batch-actions" v-if="selectedShipments.length > 0">
      <el-button type="primary" size="large" @click="handleBatchOutbound">
        批量出库 ({{ selectedShipments.length }})
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const { proxy } = getCurrentInstance();

// 搜索表单
const searchForm = reactive({
  shipment_no: '',
  order_no: '',
  product_name: ''
});

// 发货列表
const shipmentList = ref([]);
const loading = ref(false);

// 分页
const pagination = reactive({
  page: 1,
  rows: 10,
  total: 0
});

// 选中的发货记录
const selectedShipments = ref([]);

// 加载发货列表
const loadShipments = async () => {
  loading.value = true;
  try {
    const wheres = [];
    
    // 构建查询条件
    if (searchForm.shipment_no) {
      wheres.push({ name: 'shipment_no', value: searchForm.shipment_no });
    }
    if (searchForm.order_no) {
      wheres.push({ name: 'order_no', value: searchForm.order_no });
    }
    if (searchForm.product_name) {
      wheres.push({ name: 'product_name', value: searchForm.product_name, displayType: 'like' });
    }

    const res = await proxy.http.post('/api/shipment/getPageData', {
      page: pagination.page,
      rows: pagination.rows,
      wheres: wheres,
      sort: 'CreateDate',
      order: 'desc'
    });

    console.log('发货列表响应:', res);

    if (res && (res.status === true || res.status === 0)) {
      shipmentList.value = (res.rows || []).map(item => ({
        ...item,
        outbound_status: 0 // 默认待出库，实际应该从数据库读取
      }));
      pagination.total = res.total || 0;
    } else {
      ElMessage.error(res?.message || '加载发货列表失败');
    }
  } catch (error) {
    console.error('加载发货列表失败:', error);
    ElMessage.error('加载发货列表失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadShipments();
};

// 重置
const handleReset = () => {
  searchForm.shipment_no = '';
  searchForm.order_no = '';
  searchForm.product_name = '';
  pagination.page = 1;
  loadShipments();
};

// 分页改变
const handleSizeChange = (val) => {
  pagination.rows = val;
  pagination.page = 1;
  loadShipments();
};

const handleCurrentChange = (val) => {
  pagination.page = val;
  loadShipments();
};

// 选择改变
const handleSelectionChange = (selection) => {
  selectedShipments.value = selection.filter(item => item.outbound_status !== 1);
};

// 处理单个出库
const handleOutbound = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认对发货单【${row.shipment_no}】进行出库操作吗？<br/>
      <div style="margin-top: 10px;">
        <strong>商品名称：</strong>${row.product_name}<br/>
        <strong>发货数量：</strong>${row.Num} 件<br/>
        <strong>订单编号：</strong>${row.order_no}
      </div>`,
      '出库确认',
      {
        confirmButtonText: '确定出库',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    );

    loading.value = true;

    // 调用出库API
    const res = await proxy.http.post('/api/shipment/processOutbound', {
      shipmentNo: row.shipment_no
    });

    if (res && res.status) {
      ElMessage.success(res.message || '出库成功！');
      // 刷新列表
      await loadShipments();
    } else {
      ElMessage.error(res?.message || '出库失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('出库失败:', error);
      ElMessage.error('出库失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 批量出库
const handleBatchOutbound = async () => {
  if (selectedShipments.value.length === 0) {
    ElMessage.warning('请先选择要出库的发货单');
    return;
  }

  try {
    const count = selectedShipments.value.length;
    await ElMessageBox.confirm(
      `确认对选中的 ${count} 条发货单进行批量出库操作吗？`,
      '批量出库确认',
      {
        confirmButtonText: '确定出库',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    loading.value = true;

    let successCount = 0;
    let failCount = 0;
    const errors = [];

    // 逐个处理出库
    for (const shipment of selectedShipments.value) {
      try {
        const res = await proxy.http.post('/api/shipment/processOutbound', {
          shipmentNo: shipment.shipment_no
        });

        if (res && res.status) {
          successCount++;
        } else {
          failCount++;
          errors.push(`${shipment.shipment_no}: ${res?.message || '未知错误'}`);
        }
      } catch (error) {
        failCount++;
        errors.push(`${shipment.shipment_no}: ${error.message || '未知错误'}`);
      }
    }

    // 显示结果
    if (failCount === 0) {
      ElMessage.success(`批量出库成功！共处理 ${successCount} 条记录`);
    } else {
      ElMessage.warning(`批量出库完成！成功 ${successCount} 条，失败 ${failCount} 条`);
      if (errors.length > 0) {
        console.error('出库失败详情:', errors);
      }
    }

    // 刷新列表
    await loadShipments();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量出库失败:', error);
      ElMessage.error('批量出库失败');
    }
  } finally {
    loading.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadShipments();
});
</script>

<style scoped lang="less">
.sales-outbound-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 60px);

  .header-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 18px;
        font-weight: bold;
        color: #303133;
      }
    }

    .search-form {
      margin-top: 10px;
    }
  }

  .table-card {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .batch-actions {
    position: fixed;
    bottom: 30px;
    right: 30px;
    z-index: 999;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
  }
}
</style>

